<template>
  <el-main style="padding: 0;overflow: visible;">
    <el-container class="config-page panel-block">
      <el-header class="sa-header">
        <el-tabs class="sa-tabs" v-model="configType" @tab-change="tabChange">
          <el-tab-pane v-for="c in configList" :key="c" :label="c.label" :name="c.api"></el-tab-pane>
        </el-tabs>
      </el-header>
      <div v-show="configType === 'store'">
        <el-form :model="form" label-width="auto">
          <div class="basic-box sa-m-t-40">
            <div class="basic-box-title sa-m-b-20">基础信息</div>
            <el-form-item label="商家名称">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="商家图片">
              <sa-uploader v-model="form.thumb" fileType="image"></sa-uploader>
            </el-form-item>
            <el-form-item label="服务图片">
              <sa-uploader :multiple="true" v-model="form.service_images" fileType="image"></sa-uploader>
            </el-form-item>
            <el-form-item label="环境图片">
              <sa-uploader :multiple="true" v-model="form.path_images" fileType="image"></sa-uploader>
            </el-form-item>
            <el-form-item label="相册">
              <sa-uploader :multiple="true" v-model="form.photo_images" fileType="image"></sa-uploader>
            </el-form-item>
            <el-form-item label="售后电话">
              <el-input v-model="form.mobile" />
            </el-form-item>
            <el-form-item label="人均消费">
              <el-input type="number" v-model="form.per_pay" />
            </el-form-item>
            <el-form-item label="评分">
              <el-input type="number" v-model="form.mark" />
            </el-form-item>
            <el-form-item label="扩展标签">
              <el-input v-model="form.category_tag" />
            </el-form-item>
            <el-form-item label="品牌LOGO">
              <sa-uploader v-model="form.icon" fileType="image"></sa-uploader>
            </el-form-item>
            <el-form-item label="品牌简介">
              <el-input v-model="form.intro" />
            </el-form-item>
            <el-form-item label="品牌名称">
              <el-input v-model="form.brand_name" />
            </el-form-item>
            <el-form-item label="商家行业">
              <el-input v-model="form.category_text" disabled />
            </el-form-item>
            <el-form-item label="保证金">
              <el-input v-model="form.security_deposit" disabled placeholder="请输入保证金" class="sa-w-160" type="number"
                        :step="0.01" :min="0" :precision="2">
                <template #append>元</template>
              </el-input>
              <div class="bail" v-if="is_deposit_paid === 0" @click="payment">未缴纳，点击缴纳</div>
            </el-form-item>
            <el-form-item label="店铺地址">
              <div style="width: 400px;height: 380px">
                <el-amap ref="mapRef" :min-zoom="10" :max-zoom="22" :center="aMap.center" :zoom="aMap.zoom"
                         @init="mapInit"
                         @click="mapClick">
                         <el-amap-marker
                          v-for="(marker, index) in markers"
                          :key="index + '1'"
                          :position="marker"
                        />
                  <el-amap-search-box
                    placeholder="输入地址搜索"
                    :visible="aMap.visible"
                    :debounce="1000"
                    @select="selectPoi"
                    @choose="selectPoi"
                  />
                </el-amap>
              </div>
            </el-form-item>
            <el-form-item label="经营时间">
              <el-table stripe :data="timeData" border style="width: 710px;border-radius: 2px">
                <el-table-column label="周期选择" align="center" width="430">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.cycle"
                      multiple
                      placeholder="请选择周期"
                    >
                      <el-option
                        v-for="item in time_template"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="level_2" label="营业时间" align="center" width="280">
                  <template #default="scope">
                    <div class="sa-flex">
                      <div style="width: 120px;">
                        <el-time-picker v-model="scope.row.time_begin" placeholder="00:00:00" />
                      </div>
                      <div style="margin: 0 12px;">至</div>
                      <div style="width: 120px;">
                        <el-time-picker v-model="scope.row.time_end" placeholder="00:00:00" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label=" ">
              <el-button @click="getData()">重置</el-button>
              <el-button type="primary" @click="keepForm">保存</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div v-show="configType === 'industry'">
        <div class="basic-box sa-m-t-40">
          <div class="sa-flex sa-row-between sa-col-center sa-m-b-20">
            <div class="basic-box-title">类目信息</div>
          </div>
          <div class="sa-flex sa-row-between sa-col-top">
            <div>
              <div class="sa-flex sa-col-top">
                <div class="aptitude-title sa-m-r-40">经营类目</div>
                <el-table stripe :data="operate.left" border style="width: 635px;border-radius: 2px">
                  <el-table-column prop="parent.name" label="一级类目" align="center" width="115" />
                  <el-table-column prop="name" label="二级类目" align="center" width="200" />
                  <el-table-column label="三级类目" align="center" width="200">
                    <template #default="scope">
                      <div>-</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="资质" align="center" width="120">
                    <template #default="scope">
                      <el-button
                        v-auth="'seller.admin.info.aptitude.details'"
                        class="is-link"
                        type="primary"
                        v-if="scope.row.audit_status === 'normal'"
                        @click="aptitude_details(scope.row,1,'left')"
                      >查看
                      </el-button>
                      <el-button
                        class="is-link"
                        type="danger"
                        v-else-if="scope.row.audit_status === 'disabled'"
                      >禁用
                      </el-button>
                      <el-button
                        class="is-link"
                        type="warning"
                        v-else-if="scope.row.audit_status === 'apply'"
                      >审核中
                      </el-button>
                      <el-button
                        v-auth="'seller.admin.info.aptitude.look'"
                        class="is-link"
                        type="danger"
                        v-else-if="scope.row.audit_status === 'reject'"
                        @click="aptitude_details(scope.row,2,'left')"
                      >
                        <div style="display: flex;flex-direction: column;font-size: 12px;">
                          <div>未通过</div>
                          <div class="sa-m-t-5">点击查看反馈</div>
                        </div>
                      </el-button>
                      <el-button
                        v-auth="'seller.admin.info.aptitude.apply'"
                        class="is-link"
                        type="primary"
                        v-else
                        @click="apply_aptitude(scope.row,'left')"
                      >申请类目
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div>
              <div class="sa-flex sa-col-top">
                <div class="aptitude-title sa-m-r-40">资质经营类目</div>
                <el-table stripe :data="operate.right" border style="width: 635px;border-radius: 2px">
                  <el-table-column prop="parent.name" label="一级类目" align="center" width="115" />
                  <el-table-column prop="name" label="二级类目" align="center" width="200" />
                  <el-table-column label="三级类目" align="center" width="200">
                    <template #default="scope">
                      <div>-</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="资质" align="center" width="120">
                    <template #default="scope">
                      <el-button
                        v-auth="'seller.admin.info.aptitude.details'"
                        class="is-link"
                        type="primary"
                        v-if="scope.row.audit_status === 'normal'"
                        @click="aptitude_details(scope.row,1,'right')"
                      >查看
                      </el-button>
                      <el-button
                        class="is-link"
                        type="primary"
                        v-else-if="scope.row.audit_status === 'disabled'"
                      >禁用
                      </el-button>
                      <el-button
                        class="is-link"
                        type="warning"
                        v-else-if="scope.row.audit_status === 'apply'"
                      >审核中
                      </el-button>
                      <el-button
                        v-auth="'seller.admin.info.aptitude.look'"
                        class="is-link"
                        type="danger"
                        v-else-if="scope.row.audit_status === 'reject'"
                        @click="aptitude_details(scope.row,2,'right')"
                      >
                        <div style="display: flex;flex-direction: column;font-size: 12px;">
                          <div>未通过</div>
                          <div class="sa-m-t-5">点击查看反馈</div>
                        </div>
                      </el-button>
                      <el-button
                        v-auth="'seller.admin.info.aptitude.apply'"
                        class="is-link"
                        type="primary"
                        v-else
                        @click="apply_aptitude(scope.row,'right')"
                      >申请类目
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="takeaway" v-show="configType === 'brand'">
        <div class="basic-box sa-m-t-40">
          <div class="sa-flex sa-row-between sa-col-center sa-m-b-20">
            <div class="basic-box-title">品牌授权</div>
            <el-button type="primary" @click="addBrand">添加</el-button>
          </div>
          <el-table stripe :data="brand.data" border style="width: 1512px;border-radius: 2px;">
            <el-table-column label="品牌LOGO" align="center" width="240">
              <template #default="scope">
                <div style="display: flex;justify-content: center;">
                  <sa-preview :url="scope.row.logo" size="100"></sa-preview>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="trademark_registration_number" label="商标注册号" align="center" width="170" />
            <el-table-column prop="" label="所属类目" align="center" width="360">
              <template #default="scope">
                <div>{{ scope.row.category_text || '-' }}</div>
              </template>
            </el-table-column>
            <el-table-column label="资质证书" align="center" width="300">
              <template #default="scope">
                <div style="display: flex;justify-content: flex-start;overflow-y: scroll">
                  <div class="sa-m-r-10" v-for="(item,index) in JSON.parse(scope.row.qualification_certificate)" :key="index">
                    <sa-preview :url="item" size="80"></sa-preview>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="goods" label="有效时间" align="center" width="227">
              <template #default="scope">
                <div v-if="scope.row.auth_type === 'permanent'">长期有效</div>
                <div v-if="scope.row.auth_type === 'fixed'">{{ JSON.parse(scope.row.expiration_date)[0] }}</div>
                <div v-if="scope.row.auth_type === 'fixed'">{{ JSON.parse(scope.row.expiration_date)[1] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="资质状态" align="center" width="215">
              <template #default="scope">
                <el-button
                  class="is-link"
                  v-if="Number(scope.row.audit_status) === 0"
                  type="warning">审核中
                </el-button>
                <el-button
                  class="is-link"
                  v-if="Number(scope.row.audit_status) === 1"
                  @click="addBrand(scope.row,2)"
                  type="primary">查看
                </el-button>
                <el-button
                  class="is-link"
                  v-if="Number(scope.row.audit_status) === 2"
                  @click="addBrand(scope.row,3)"
                  type="primary">审核驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-container>
  </el-main>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElAmap } from '@vuemap/vue-amap';
  import { api } from '../../info.service';
  import { cloneDeep } from 'lodash';
  import { ElMessage } from 'element-plus';
  import dayjs from 'dayjs'
  import { useModal } from '@/sheep/hooks';
  import pay from '../dialog/pay.vue';
  import update from '@/app/seller/admin/info/aptitude/dialog/update.vue';
  import details from '@/app/seller/admin/info/aptitude/dialog/details.vue';
  import add_brand from '../dialog/addBrand.vue';

  const configType = ref('store');

  const configList = [
    { label: '商家信息', api: 'store' },
    { label: '行业资质', api: 'industry' },
    { label: '品牌资质', api: 'brand' },
  ];

  const time_template = [
    {
      value: 'monday',
      label: '周一',
    },
    {
      value: 'tuesday',
      label: '周二',
    },
    {
      value: 'wednesday',
      label: '周三',
    },
    {
      value: 'thursday',
      label: '周四',
    },
    {
      value: 'friday',
      label: '周五',
    },
    {
      value: 'saturday',
      label: '周六',
    },
    {
      value: 'sunday',
      label: '周日',
    },
  ];

  const is_deposit_paid = ref(1);
  const url = ref('');
  const markers = ref([]);

  const form = reactive({
    type: 3,
    name: '',
    thumb: '',
    mobile: '',
    longitude: '',
    latitude: '',
    address: '',
    category_text: '',
    security_deposit: '',
    icon:'',
    brand_name:'',
    intro:'',
    service_images: [],
    path_images: [],
    photo_images: [],
    per_pay: 0,
    mark:0,
    category_tag:''
  });

  const operate = reactive({
    left: [],
    right: [],
  });

  const brand = reactive({
    data: [],
  });

  const timeData = reactive([
    {
      cycle: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'],
      time_begin: '',
      time_end: '',
    },
  ]);

  const aMap = reactive({
    map: null,
    marker: '',
    zoom: 15,
    center: [120.252165, 30.235495],
    visible: true,
  });

  onMounted(() => {
    getData();
  });

  const addBrand = (item, type = 1) => {
    // 1 添加
    // 2 查看详情
    // 3 重新提交审核
    useModal(
      add_brand,
      {
        title: '添加品牌资质',
        type: form.type,
        show_type: type,
        id: item.id,
      },
      {
        confirm: () => {
          getBrand();
        },
      },
    );
  };

  const tabChange = (e) => {
    if (e === 'store') {
      getData();
    }
    if (e === 'industry') {
      getAptitude();
    }

    if (e === 'brand') {
      getBrand();
    }
  };

  // 保证金支付
  const payment = () => {
    useModal(
      pay,
      {
        title: '保证金支付',
      },
      {
        confirm: () => {
        },
      },
    );
  };

  const reapply_aptitude = (item, type) => {
    if (type === 'left') {
      return apply_request(item.id);
    }
    useModal(
      update,
      {
        title: '资质证明',
        id: item.id,
        type: form.type,
        ilk: 2,
        c_id: item.c_id,
      },
      {
        confirm: () => {
          ElMessage({
            message: '申请成功',
            type: 'success',
          });
          getAptitude();
        },
      },
    );
  };
  // 弹出申请资质
  const apply_aptitude = (item, type) => {
    if (type === 'left') {
      return apply_request(item.id);
    }
    useModal(
      update,
      {
        title: '资质证明',
        id: item.id,
        type: form.type,
        ilk: 1,
      },
      {
        confirm: () => {
          ElMessage({
            message: '申请成功',
            type: 'success',
          });
          getAptitude();
        },
      },
    );
  };

  // 资质申请 申请
  const apply_request = async (id) => {
    const { error, data } = await api.aptitude.apply_aptitude({
      type: form.type,
      category_id: id,
    });

    if (error === 0) {
      ElMessage({
        message: '申请成功',
        type: 'success',
      });
      await getAptitude();
    }
  };

  // 资质申请 再次申请
  const reapply_request = async (id) => {
    const { error, data } = await api.aptitude.reapply_aptitude({
      type: form.type,
      category_id: id,
    });

    if (error === 0) {
      ElMessage({
        message: '申请成功',
        type: 'success',
      });
      await getAptitude();
    }
  };

  // 查看资质详情
  const aptitude_details = (item, type, ilk) => {
    // type === 1 查看详情
    // type === 2 查看驳回详情
    useModal(
      details,
      {
        title: type === 1 ? '资质证明' : '驳回信息',
        type: type,
        url: ilk === 'left' ? [url.value] : item.industry_qualification.split(','),
        remarks: item.remarks,
      },
      {
        confirm: () => {
          if (ilk === 'right') {
            reapply_aptitude(item, 'right');
          } else {
            reapply_request(item.id);
          }
        },
      },
    );
  };

  const keepForm = async () => {
    let temp = cloneDeep(form);
    let time_temp = cloneDeep(timeData);
    // 转换成文字时间
    const begin = dayjs(time_temp[0].time_begin);
    const end = dayjs(time_temp[0].time_end);
    // 判断是否选择了营业时间 没有的话默认空 否则再次编辑会报错
    if (time_temp[0].time_begin) {
      time_temp[0].time_begin = begin.format('HH:mm:ss');
    } else {
      time_temp[0].time_begin = '';
    }
    if (time_temp[0].time_end) {
      time_temp[0].time_end = end.format('HH:mm:ss');
    } else {
      time_temp[0].time_end = '';
    }
    temp.business_rule = JSON.stringify(time_temp);
    const regex = /^https:\/\//;
    temp.service_images = temp.service_images.map(item => {
      return regex.test(item) ? item : `https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com${item}`
    });
    temp.path_images = temp.path_images.map(item => {
      return regex.test(item) ? item :`https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com${item}`
    });
    temp.photo_images = temp.photo_images.map(item => {
      return regex.test(item) ? item :`https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com${item}`
    });
    temp.thumb = regex.test(temp.thumb) ? temp.thumb :`https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com${temp.thumb}`
    temp.icon = regex.test(temp.icon) ? temp.icon :`https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com${temp.icon}`
    delete temp.category_text;
    delete temp.security_deposit;
    const { error } = await api.aptitude.update_store(temp);
    if (error === 0) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      });
    }
  };

  const getData = async () => {
    const { error, data } = await api.aptitude.store({ type: form.type });

    if (error === 0) {
      form.name = data.name;
      form.thumb = data.thumb;
      form.mobile = data.mobile;
      form.longitude = data.longitude;
      form.latitude = data.latitude;
      form.address = data.address;
      // 强制给输入框添加默认值
      form.category_text = data.category_text;
      form.security_deposit = data.security_deposit;
      is_deposit_paid.value = data.is_deposit_paid;
      form.icon = data.icon;
      form.brand_name = data.brand_name;
      form.intro = data.intro;
      form.service_images = data.service_images ? JSON.parse(data.service_images) : [];
      form.path_images = data.path_images ? JSON.parse(data.path_images) : [];
      form.photo_images = data.photo_images ? JSON.parse(data.photo_images) : [];
      form.per_pay = data.per_pay;
      form.mark = data.mark;
      form.category_tag = data.category_tag

      if (data.address) {
        document.querySelector('.el-vue-search-box-container input').value = data.address;
      }
      if (data.longitude && data.latitude) {
        // addMarker(Number(data.longitude), Number(data.latitude));
        markers.value=[[data.longitude,data.latitude]]
        aMap.center = [data.longitude,data.latitude];
      }
      if (data.business_rule) {
        timeData[0].cycle = JSON.parse(data.business_rule)[0].cycle;
        timeData[0].time_begin = JSON.parse(data.business_rule)[0].time_begin === 'Invalid Date' ? '' : dayjs(`${dayjs().format('YYYY-MM-DD')}${JSON.parse(data.business_rule)[0].time_begin}`).toDate();
        timeData[0].time_end = JSON.parse(data.business_rule)[0].time_end === 'Invalid Date' ? '' : dayjs(`${dayjs().format('YYYY-MM-DD')}${JSON.parse(data.business_rule)[0].time_end}`).toDate();
      }
    }
  };

  const getAptitude = async () => {
    const { error, data } = await api.aptitude.aptitude_info({ type: form.type });
    if (error === 0) {
      operate.left = data.proof_required_0;
      operate.right = data.proof_required_1;
    }
  };

  // 获取品牌列表
  const getBrand = async () => {
    const { error, data } = await api.aptitude.brand_info({ type: form.type });
    if (error === 0) {
      brand.data = data;
    }
  };


  // 以下是获取经纬度和地址的方法
  const selectPoi = (e) => {
    const { poi } = e;
    if (!poi.location) return;
    form.address = poi.district + poi.name;
    mapClick({
      lnglat: poi.location,
    });
  };

  const mapInit = (o) => {
    aMap.map = o;
  };
  const mapClick = (e) => {
    let lnglat = `${e.lnglat.lng},${e.lnglat.lat}`;
    // console.log(e);
    form.latitude = `${e.lnglat.lat}`;
    form.longitude = `${e.lnglat.lng}`;
    markers.value=[[e.lnglat.lng,e.lnglat.lat]]
    aMap.center = [e.lnglat.lng,e.lnglat.lat];
    // coordinateAdd(lnglat);
  };
  const addMarker = (lng = 121.59996, lat = 31.177646) => {
    if (aMap.marker) {
      aMap.map.remove(aMap.marker);
    }
    aMap.marker = new aMap.Marker({
      position: [lng, lat],
    });
    aMap.map.add(aMap.marker);
  };

  const coordinateAdd = (e) => {
    let lnglat = String(e).split(',');
    if (lnglat.length === 2) {
      aMap.center = [Number(lnglat[0]), Number(lnglat[1])];
      addMarker(Number(lnglat[0]), Number(lnglat[1]));
    }
  };
</script>

<style scoped lang="scss">
  .basic-box {
    .basic-box-title {
      width: max-content;
      position: relative;
      font-family: 'PingFangSC-Regular, sans-serif';
      font-size: 14px;
      color: #3D3D3D;
      z-index: 0;
    }

    .basic-box-title::after {
      pointer-events: none;
      content: "";
      position: absolute;
      height: 8px;
      background: var(--t-bg-active);
      bottom: 0;
      right: 0;
      left: 0;
      z-index: -1;
    }

    .basic-box-item {
      padding-left: 40px;
      margin-top: 20px;

      .basic-box-item-label {
        min-width: 100px;
        font-family: 'PingFangSC-Regular, sans-serif';
        font-size: 14px;
        color: #3D3D3D;
        margin-right: 20px;
      }

      .basic-box-item-text {
        font-family: 'PingFangSC-Regular, sans-serif';
        font-size: 14px;
        color: #3D3D3D;
      }

      .basic-box-item-image {
        width: 225px;
        height: 150px;
        margin-right: 40px;
      }
    }
  }

  .aptitude-title {
    font-family: 'Source Han Sans CN';
    font-size: 14px;
    color: #3D3D3D;
  }

  .takeaway {
    display: flex;
    justify-content: center;
  }

  .bail {
    margin-left: 10px;
    font-size: 12px;
    color: #FD5D5D;
  }
</style>